const api = require('../../../../ws_micro_shop/utils/api.js');
const tools = require('../../../../ws_micro_shop/utils/getuserinfo.js');
const app = getApp();

let is_no_more = false;
let is_loading = false;
let p = 2;
let timer = null;
let dingshi = null;

Page({
  data: {
    hide: 1,
    qrcode: '',
    scrollLeft: 0,
    scrollTop: 0,
    show_index: false,
    theme: app.themeData,
    showpaytypes: false,
    unit: '',
    currVal: '',
    isEmpty: true,
    keywords: '',
    useTabbar: !(app.tabbarindex === 0 && app.siteInfo.tabbar_type === '1'),
    imgUrl: app.imgUrl,
  },
  onLoad(opts) {
    let that = this;
    let options = opts || {};
    let pages = getCurrentPages();
    app.tabbarindex = options.tabbarindex ? options.tabbarindex - 0 : app.tabbarindex;
    let userinfo = wx.getStorageSync('user_info');
    app.loadCurrencyUnit().then(res => {
      that.setData({
        unit: res.unit,
      });
    });
    Number(userinfo.info) === 0 && tools.onGetInfo(this, userinfo.auth_mode);
    this.systemInfo = wx.systemInfo;
    let store = wx.getStorageSync('store');
    let isBrand = app.ws_micro_shop_globalData && app.ws_micro_shop_globalData.isBrand; 
    this.setData({
      store,
      opts: options,
      status: options.status || -1,
      isBrand,
    });
    app.pageOnLoad(this);
    is_no_more = false;
    is_loading = false;
    p = 2;
    let scrollLeft = 0;
    options.status >= 2 ? scrollLeft = 600 : scrollLeft = 0;
    this.setData({
      scrollLeft,
    });
    if (pages.length === 1) {
      this.setData({
        show_index: true,
      });
    }
  },
  onShow() {
    is_no_more = false;
    is_loading = false;
    p = 2;
    this.loadOrderList(this.data.status);
  },
  onHide() {
    timer && clearInterval(timer);
    dingshi && clearInterval(dingshi);
  },
  onUnload() {
    timer && clearInterval(timer);
    dingshi && clearInterval(dingshi);
  },
  loadOrderList(stas, k = '') {
    let status = stas;
    if (!status) {
      status = -1;
    }
    let _this = this;
    _this.setData({
      status,
    });
    wx.showLoading({
      title: '正在加载',
      mask: true,
    });
    app.ws_micro_shoprequest({
      url: api.group.order.list,
      data: {
        status: _this.data.status,
        keywords: k,
      },
      success: function (res) {
        if (res.code === 0) {
          _this.setData({
            order_list: res.data.list,
          });
        }
        _this.setData({
          show_no_data_tip: (res.data.list.length === 0),
        });
        if (timer) {
          timer && clearInterval(timer);
        }
        if (Number(status) !== 4) {
          _this.countDown();
        }
      },
      complete: function () {
        wx.hideLoading();
      },
    });
  },
  countDown() {
    let _this = this;
    timer = setInterval(function () {
      let order_list = _this.data.order_list;
      for (let i in order_list) {
        if ({}.hasOwnProperty.call(order_list, i) && (order_list[i].status === 2)) {
          let leftTime = (new Date(order_list[i]['limit_time_ms'][0], order_list[i]['limit_time_ms'][1] - 1, order_list[i]['limit_time_ms'][2], order_list[i]['limit_time_ms'][3], order_list[i]['limit_time_ms'][4], order_list[i]['limit_time_ms'][5])) - (new Date());
          let days = parseInt(leftTime / 1000 / 60 / 60 / 24, 10);
          let hours = parseInt(leftTime / 1000 / 60 / 60 % 24, 10);
          let minutes = parseInt(leftTime / 1000 / 60 % 60, 10);
          let seconds = parseInt(leftTime / 1000 % 60, 10);
          days = _this.checkTime(days);
          hours = _this.checkTime(hours);
          minutes = _this.checkTime(minutes);
          seconds = _this.checkTime(seconds);
          order_list[i].limit_time = {
            days: days,
            hours: hours > 0 ? hours : '00',
            mins: minutes > 0 ? minutes : '00',
            secs: seconds > 0 ? seconds : '00',
          };
          _this.setData({
            order_list,
          }, () => {
            // Number(hours) === 0 && Number(minutes) === 0 && Number(seconds) === 0 && _this.loadOrderList(_this.data.status);
          });
        }
      }
    }, 1000);
  },
  checkTime(pmsI) {
    let i = pmsI;
    i = i > 0 ? i : 0;
    if (i < 10) {
      i = '0' + i;
    }
    return i;
  },
  onReachBottom() {
    timer && clearInterval(timer);
    let _this = this;
    if (is_loading || is_no_more) {
      return;
    }
    is_loading = true;
    app.ws_micro_shoprequest({
      url: api.group.order.list,
      data: {
        status: _this.data.status,
        page: p,
        keywords: _this.data.keywords,
      },
      success: function (res) {
        if (res.code === 0) {
          let order_list = _this.data.order_list.concat(res.data.list);
          _this.setData({
            order_list,
          });
          if (res.data.list.length === 0) {
            is_no_more = true;
          }
          if (Number(_this.data.status) !== 4) {
            _this.countDown();
          }
        }
        p++;
      },
      complete: function () {
        is_loading = false;
      },
    });
  },
  goHome() {
    app.util.navigateTo('/ws_micro_shop_pt/pages/pt/index/index', {}, true);
  },
  showPayType(e) {
    let dataset = e.currentTarget.dataset;
    this.setData({
      showpaytypes: true,
      group: dataset.group,
      orderID: dataset.id,
      pay_type_list: dataset.payment,
      discountId: e.currentTarget.dataset.discount == 1 ? e.currentTarget.dataset.payment1 : -1,
    });
  },
  disabledClick() {
    // it`s necessary
  },
  hidePayType() {
    this.setData({
      showpaytypes: false,
    });
  },
  orderPay(e) {
    let payment = Number(e.currentTarget.dataset.payment);
    let id = this.data.orderID;
    wx.showLoading({
      title: '正在提交',
      mask: true,
    });
    this.setData({
      showpaytypes: false,
    });
    if (payment === 0) {
      this.WechatPay(id);
    } else if (payment === 3) {
      this.setData({
        showpaytypes: false,
      });
      this.BalancePay(id);
    } else if (payment === 5) {
      if (wx.getStorageSync('user_info').unionid && wx.getStorageSync('user_info').card) {
        this.CardPay(id);
      } else {
        wx.hideLoading();
        wx.showModal({
          title: '友情提示',
          content: '你还未开通会员卡，是否前往个人中心开通？',
          success: function (res) {
            if (res.confirm) {
              app.util.navigateTo('/ws_micro_shop/pages/user/user', {}, false);
            }
          },
        });
      }
    }
  },
  WechatPay(id) {
    let group = Number(this.data.group);
    app.ws_micro_shoprequest({
      url: api.group.pay_data,
      data: {
        order_id: id,
        pay_type: 'WECHAT_PAY',
      },
      complete: function () {
        wx.hideLoading();
      },
      success: function (res) {
        if (res.code === 0) {
          wx.requestPayment({
            timeStamp: res.data.timeStamp,
            nonceStr: res.data.nonceStr,
            package: res.data.package,
            signType: res.data.signType,
            paySign: res.data.paySign,
            complete: function (e) {
              if (e.errMsg === 'requestPayment:fail' || e.errMsg === 'requestPayment:fail cancel') {
                wx.showModal({
                  title: '提示',
                  content: '订单尚未支付',
                  showCancel: false,
                  confirmText: '确认',
                  success: function (res) {
                    if (res.confirm) {
                      app.util.navigateTo('/ws_micro_shop_pt/pages/pt/order/order', { status: 0 }, true);
                    }
                  },
                });
                return;
              }
              if (group === 1) {
                app.util.navigateTo('/ws_micro_shop_pt/pages/pt/order/order', { status: 1 }, true);
              } else {
                app.util.navigateTo('/ws_micro_shop_pt/pages/pt/order/order', { status: 2 }, true);
              }
            },
          });
        }
        if (res.code === 1) {
          wx.showToast({
            title: res.msg || '',
            icon: 'none',
          });
        }
      },
    });
  },
  BalancePay(id) {
    let group = Number(this.data.group);
    app.ws_micro_shoprequest({
      url: api.group.pay_data,
      data: {
        order_id: id,
        pay_type: 'BALANCE_PAY',
      },
      complete: function () {
        wx.hideLoading();
      },
      success: function (res) {
        if (res.code === 0) {
          if (group === 1) {
            app.util.navigateTo('/ws_micro_shop_pt/pages/pt/order/order', { status: 1 }, true);
          } else {
            app.util.navigateTo('/ws_micro_shop_pt/pages/pt/order/order', { status: 2 }, true);
          }
        }
        if (res.code === 1) {
          wx.showModal({
            title: '提示',
            content: res.msg,
            showCancel: false,
          });
        }
      },
    });
  },
  CardPay(id) {
    let group = Number(this.data.group);
    app.ws_micro_shoprequest({
      url: api.group.pay_data,
      data: {
        order_id: id,
        pay_type: 'CARD_PAY',
      },
      complete: function () {
        wx.hideLoading();
      },
      success: function (res) {
        if (res.code === 0) {
          if (group === 1) {
            app.util.navigateTo('/ws_micro_shop_pt/pages/pt/order/order', { status: 1 }, true);
          } else {
            app.util.navigateTo('/ws_micro_shop_pt/pages/pt/order/order', { status: 2 }, true);
          }
        }
        if (res.code === 1) {
          wx.showModal({
            title: '提示',
            content: res.msg,
            showCancel: false,
          });
        }
      },
    });
  },
  goToGroup(e) {
    wx.navigateTo({
      url: '/ws_micro_shop_pt/pages/pt/group/details?oid=' + e.currentTarget.dataset.id,
    });
  },
  getOfflineQrcode(e) {
    let _this = this;
    let orderId = e.currentTarget.dataset.id;
    wx.showLoading({
      title: '正在加载',
      mask: true,
    });
    app.ws_micro_shoprequest({
      url: api.group.order.get_qrcode,
      data: {
        order_no: e.currentTarget.dataset.no,
      },
      success: function (res) {
        if (res.code === 0) {
          _this.setData({
            hide: 0,
            qrcode: res.data.url,
          });
          if (dingshi) {
            dingshi && clearInterval(dingshi);
          }
          _this.Loop(orderId);
        } else {
          wx.showModal({
            title: '提示',
            content: res.msg,
          });
        }
      },
      complete: function () {
        wx.hideLoading();
      },
    });
  },
  hide(e) {
    dingshi && clearInterval(dingshi);
    this.setData({
      hide: 1,
    });
  },
  goToCancel(e) {
    let _this = this;
    wx.showModal({
      title: '提示',
      content: '是否取消该订单？',
      cancelText: '否',
      confirmText: '是',
      success: function (res) {
        if (res.cancel) {
          return true;
        }
        if (res.confirm) {
          wx.showLoading({
            title: '操作中',
          });
          app.ws_micro_shoprequest({
            url: api.group.order.revoke,
            data: {
              order_id: e.currentTarget.dataset.id,
            },
            success: function (res) {
              wx.hideLoading();
              wx.showModal({
                title: '提示',
                content: res.msg,
                showCancel: false,
                success: function (res) {
                  if (res.confirm) {
                    _this.loadOrderList(_this.data.status);
                  }
                },
              });
            },
          });
        }
      },
    });
  },
  switchNav(e) {
    let status = e.currentTarget.dataset.status;
    is_no_more = false;
    is_loading = false;
    p = 2;
    this.loadOrderList(status);
  },
  goToRefundDetail(e) {
    let id = e.currentTarget.dataset.refund_id;
    wx.navigateTo({
      url: '/ws_micro_shop/pages/order-refund-detail/order-refund-detail?id=' + id + '&entry=pt',
    });
  },
  Loop(id) {
    let _this = this;
    dingshi = setInterval(function () {
      app.ws_micro_shoprequest({
        url: api.default.orderClerk,
        data: {
          order_id: id,
          type: 'pt',
        },
        success: function (res) {
          if (res.code === 0) {
            if (Number(res.data) === 1) {
              dingshi && clearInterval(dingshi);
              _this.setData({
                hide: 1,
              });
              _this.loadOrderList(_this.data.status);
            }
          } else {
            wx.showModal({
              title: '提示',
              content: res.msg,
            });
          }
        },
      });
    }, 2000);
  },
  onNavigate(e) {
    let param = e.currentTarget.dataset;
    app.ws_micro_shop_navigate(param);
  },
  collectFormId(e) {
    app.collectFormId(e);
  },
  deleteOrder(e) {
    let that = this;
    let { orderid: order_id, idx } = e.currentTarget.dataset;
    let orderlist = that.data.order_list;
    wx.showModal({
      title: '提示',
      content: '是否要删除该订单',
      success: res => {
        if (res.confirm) {
          app.ws_micro_shoprequest({
            url: api.order.deleteorder,
            data: {
              order_id,
              type: 'pt',
            },
            success: function (res) {
              if (res.code === 0) {
                orderlist.splice(idx, 1);
                that.setData({
                  order_list: orderlist,
                });
                wx.showToast({
                  title: '删除成功',
                  icon: 'success',
                });
              } else {
                wx.showToast({
                  title: res.msg || '删除失败',
                  icon: 'none',
                });
              }
            },
          });
        }
      },
    });
  },
  inputChange(e) {
    let val = e.detail.value;
    if (val.trim()) {
      this.setData({
        isEmpty: false,
      });
    } else {
      this.setData({
        isEmpty: true,
      });
    }
    this.setData({
      currVal: val,
    });
  },
  clearTxt() {
    let status = this.data.status;
    is_no_more = false;
    is_loading = false;
    p = 2;
    this.setData({
      currVal: '',
      keywords: '',
      order_list: [],
      isEmpty: true,
    });
    this.loadOrderList(status);
  },
  searchTxt(keyword) {
    let keywords = keyword;
    let status = this.data.status;
    is_no_more = false;
    is_loading = false;
    p = 2;
    this.setData({
      keywords,
      order_list: [],
    });
    this.loadOrderList(status, keywords);
  },
  searchSure() {
    let keyword = (this.data.currVal).trim();
    this.searchTxt(keyword);
  },
  godetail(e){
    wx.navigateTo({
      url: '/ws_micro_shop_pt/pages/pt/order-details/order-details?id='+e.currentTarget.id,
      success: function(res) {},
      fail: function(res) {},
      complete: function(res) {},
    })
  },
});
